<template>
  <view class="my-orders">
    <!-- Tab切换 -->
    <view class="tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{ active: activeTab === index }"
        @click="handleTabChange(index)"
      >
        {{ tab.name }}
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view 
      scroll-y 
      class="order-list"
      @scrolltolower="handleLoadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="handleRefresh"
    >
      <!-- 空状态 -->
      <view v-if="orderList.length === 0 && !loading" class="empty-state">
        <view class="empty-icon">📦</view>
        <view class="empty-text">暂无接单记录</view>
        <button class="btn-go-available" @click="handleGoAvailable">去接单</button>
      </view>

      <!-- 订单卡片 -->
      <view 
        v-for="order in orderList" 
        :key="order.id"
        class="order-card"
        @click="handleViewDetail(order.id)"
      >
        <!-- 头部 -->
        <view class="order-header">
          <view class="left">
            <text class="icon">{{ getCategoryIcon(order.categoryName) }}</text>
            <text class="name">{{ order.categoryName }}</text>
          </view>
          <view class="status" :style="{ color: getStatusColor(order) }">
            {{ getDisplayStatusText(order) }}
          </view>
        </view>

        <!-- 地址信息 -->
        <view class="address-section">
          <view class="address-item">
            <view class="label">📍 取件</view>
            <view class="value">{{ order.pickupAddress }}</view>
          </view>
          <view class="divider"></view>
          <view class="address-item">
            <view class="label">🏠 送达</view>
            <view class="value">{{ order.deliveryAddress }}</view>
          </view>
        </view>

        <!-- 订单信息 -->
        <view class="order-info">
          <view class="info-row">
            <text class="label">订单金额:</text>
            <text class="earning">¥{{ order.totalAmount }}</text>
          </view>
          <view class="info-row">
            <text class="label">发布人:</text>
            <text class="value">{{ order.userName }}</text>
          </view>
          <view class="info-row">
            <text class="label">时间:</text>
            <text class="value">{{ order.acceptTime || order.createTime }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="order-actions">
          <!-- 待取件 -->
          <template v-if="order.status === 2">
            <button class="btn-text" @click.stop="handleContact(order)">联系发布人</button>
            <button class="btn-primary" @click.stop="showPickupUpload(order)">确认取件</button>
          </template>

          <!-- 配送中 -->
          <template v-else-if="order.status === 3">
            <button class="btn-text" @click.stop="handleContact(order)">联系发布人</button>
            <button class="btn-primary" @click.stop="showDeliverUpload(order)">确认送达</button>
          </template>

          <!-- 待结算 -->
          <template v-else-if="order.status === 5">
            <button class="btn-text" @click.stop="handleViewDetail(order.id)">查看详情</button>
            <!-- 未结算：显示申请结算按钮 -->
            <button 
              v-if="!order.settlementStatus || order.settlementStatus === 0" 
              class="btn-primary" 
              @click.stop="handleApplySettlement(order)"
            >
              申请结算
            </button>
            <!-- 申请中：显示申请中状态（禁用） -->
            <button 
              v-else-if="order.settlementStatus === 1" 
              class="btn-disabled" 
              disabled
            >
              申请中
            </button>
            <!-- 已结算：显示已结算状态 -->
            <button 
              v-else-if="order.settlementStatus === 2" 
              class="btn-disabled" 
              disabled
            >
              已结算
            </button>
          </template>

          <!-- 退款状态 -->
          <template v-else-if="(order.refundStatus && order.refundStatus > 0) && order.status === 9">
             <template v-if="(order.refundStatus === 1 || order.refundStatus === 2) || order.status === 9">
              <button class="btn-text" @click.stop="handleContact(order)">联系发布人</button>
            </template>
            <button class="btn-text" @click.stop="handleViewDetail(order.id)">查看详情</button>

          </template>

          <!-- 已退款且有补偿金 -->
          <template v-else-if="order.status === 8 && order.compensationAmount && order.compensationAmount > 0">
            <button class="btn-text" @click.stop="handleViewDetail(order.id)">查看详情</button>
            <!-- 未结算：显示申请结算按钮 -->
            <button 
              v-if="!order.settlementStatus || order.settlementStatus === 0" 
              class="btn-primary" 
              @click.stop="handleApplySettlement(order)"
            >
              申请结算
            </button>
            <!-- 申请中：显示申请中状态（禁用） -->
            <button 
              v-else-if="order.settlementStatus === 1" 
              class="btn-disabled" 
              disabled
            >
              申请中
            </button>
            <!-- 已结算：显示已结算状态 -->
            <button 
              v-else-if="order.settlementStatus === 2" 
              class="btn-disabled" 
              disabled
            >
              已结算
            </button>
          </template>

          <!-- 其他状态 -->
          <template v-else>
            <button class="btn-text" @click.stop="handleContact(order)">联系发布人</button>
            <button class="btn-text" @click.stop="handleViewDetail(order.id)">查看详情</button>
          </template>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading" class="loading-more">加载中...</view>
      <view v-else-if="!hasMore && orderList.length > 0" class="no-more">没有更多了</view>
    </scroll-view>

    <!-- 取件照片上传弹窗 -->
    <view class="popup-mask" v-if="showPickupPopup" @click="closePickupPopup">
      <view class="upload-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">上传取件照片</text>
          <text class="popup-close" @click="closePickupPopup">✕</text>
        </view>
        <view class="popup-content">
          <MultiImageUploader
            :images.sync="pickupImages"
            title="取件照片"
            tip="建议拍摄物品照片作为取件凭证"
            :max-count="3"
            module="order/pickup"
            @upload-success="onPickupImageUpload"
          />
        </view>
        <view class="popup-footer">
          <button class="btn-cancel" @click="closePickupPopup">取消</button>
          <button class="btn-confirm" @click="handlePickup">确认取件</button>
        </view>
      </view>
    </view>

    <!-- 送达照片上传弹窗 -->
    <view class="popup-mask" v-if="showDeliverPopup" @click="closeDeliverPopup">
      <view class="upload-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">上传送达照片</text>
          <text class="popup-close" @click="closeDeliverPopup">✕</text>
        </view>
        <view class="popup-content">
          <MultiImageUploader
            :images.sync="deliveryImages"
            title="送达照片"
            tip="建议拍摄送达现场照片作为送达凭证"
            :max-count="3"
            module="order/delivery"
            @upload-success="onDeliveryImageUpload"
          />
        </view>
        <view class="popup-footer">
          <button class="btn-cancel" @click="closeDeliverPopup">取消</button>
          <button class="btn-confirm" @click="handleDeliver">确认送达</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getPickupOrderPage, confirmPickup, confirmDeliver } from '@/api/pickup'
import { getOrderStatusDisplay, getStatusColor as getUnifiedStatusColor } from '@/utils/orderStatus'
import MultiImageUploader from '@/components/MultiImageUploader.vue'

export default {
  components: {
    MultiImageUploader
  },
  data() {
    return {
      activeTab: 0,
      tabs: [
        { name: '全部', status: null },
        { name: '待取件', status: 2 },
        { name: '配送中', status: 3 },
        { name: '待结算', status: 5 },
        { name: '已完成', status: 6 }
      ],
      orderList: [],
      loading: false,
      refreshing: false,
      hasMore: true,
      page: {
        current: 1,
        size: 10
      },
      
      // 拍照上传相关
      currentOrder: null,
      pickupImages: [],
      deliveryImages: [],
      showPickupPopup: false,
      showDeliverPopup: false
    }
  },
  onLoad() {
    this.loadOrderList()
  },
  onShow() {
    // 返回时刷新
    this.loadOrderList(true)
  },
  methods: {
    // 加载订单列表
    async loadOrderList(refresh = false) {
      if (this.loading) return
      
      if (refresh) {
        this.page.current = 1
        this.hasMore = true
        this.orderList = []
      }

      try {
        this.loading = true
        const params = {
          current: this.page.current,
          size: this.page.size,
          role: 'taker'
        }
        
        // 只有当 status 不为 null 时才添加
        if (this.tabs[this.activeTab].status !== null) {
          params.status = this.tabs[this.activeTab].status
        }
        
        const pageData = await getPickupOrderPage(params)
        
        if (refresh) {
          this.orderList = pageData.records
        } else {
          this.orderList = [...this.orderList, ...pageData.records]
        }
        
        this.hasMore = this.page.current < pageData.pages
      } catch (error) {
        console.error('加载订单失败:', error)
        uni.showToast({ title: error.msg || '加载失败', icon: 'none' })
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },

    // Tab切换
    handleTabChange(index) {
      this.activeTab = index
      this.loadOrderList(true)
    },

    // 下拉刷新
    handleRefresh() {
      this.refreshing = true
      this.loadOrderList(true)
    },

    // 加载更多
    handleLoadMore() {
      if (this.hasMore && !this.loading) {
        this.page.current++
        this.loadOrderList()
      }
    },

    // 去接单
    handleGoAvailable() {
      uni.navigateTo({
        url: '/pages/pickup/available'
      })
    },

    // 查看详情
    handleViewDetail(orderId) {
      uni.navigateTo({
        url: `/pages/pickup/detail?orderId=${orderId}`
      })
    },

    // 显示取件照片上传弹窗
    showPickupUpload(order) {
      this.currentOrder = order
      this.pickupImages = []
      this.showPickupPopup = true
    },

    // 关闭取件照片上传弹窗
    closePickupPopup() {
      this.showPickupPopup = false
      this.currentOrder = null
      this.pickupImages = []
    },

    // 取件图片上传成功
    onPickupImageUpload(data) {
      //console.log('取件图片上传成功:', data)
    },

    // 确认取件
    async handlePickup() {
      if (!this.currentOrder) return
      
      try {
        uni.showLoading({ title: '确认中...' })
        // 将图片数组转换为JSON字符串
        const pickupImagesJson = JSON.stringify(this.pickupImages)
        await confirmPickup(this.currentOrder.id, { pickupImages: pickupImagesJson })
        
        uni.hideLoading()
        uni.showToast({ title: '取件成功', icon: 'success' })
        
        // 关闭弹窗
        this.closePickupPopup()
        
        // 重新加载订单列表
        this.loadOrderList(true)
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: error.msg || '操作失败', icon: 'none' })
      }
    },

    // 显示送达照片上传弹窗
    showDeliverUpload(order) {
      this.currentOrder = order
      this.deliveryImages = []
      this.showDeliverPopup = true
    },

    // 关闭送达照片上传弹窗
    closeDeliverPopup() {
      this.showDeliverPopup = false
      this.currentOrder = null
      this.deliveryImages = []
    },

    // 送达图片上传成功
    onDeliveryImageUpload(data) {
      //console.log('送达图片上传成功:', data)
    },

    // 确认送达
    async handleDeliver() {
      if (!this.currentOrder) return
      
      try {
        uni.showLoading({ title: '确认中...' })
        // 将图片数组转换为JSON字符串
        const deliveryImagesJson = JSON.stringify(this.deliveryImages)
        await confirmDeliver(this.currentOrder.id, { deliveryImages: deliveryImagesJson })
        
        uni.hideLoading()
        uni.showToast({ title: '送达成功，等待用户确认收货', icon: 'success' })
        
        // 关闭弹窗
        this.closeDeliverPopup()
        
        // 重新加载订单列表
        this.loadOrderList(true)
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: error.msg || '操作失败', icon: 'none' })
      }
    },

    // 申请结算
    handleApplySettlement(order) {
      uni.navigateTo({
        url: `/pages/settlement/apply?orderId=${order.id}`
      })
    },

    // 联系发布人
    handleContact(order) {
      if (!order.receiverPhone) {
        uni.showToast({ title: '暂无联系方式', icon: 'none' })
        return
      }
      
      uni.showActionSheet({
        itemList: [`拨打电话: ${order.receiverPhone}`, '复制手机号'],
        success: (res) => {
          if (res.tapIndex === 0) {
            uni.makePhoneCall({ phoneNumber: order.receiverPhone })
          } else if (res.tapIndex === 1) {
            uni.setClipboardData({ data: order.receiverPhone })
          }
        }
      })
    },

    // 获取分类图标
    getCategoryIcon(categoryName) {
      const iconMap = {
        '取外卖': '🍱',
        '取快递': '📦',
        '取咖啡': '☕',
        '代买': '🛒'
      }
      return iconMap[categoryName] || '📦'
    },

    // 获取状态颜色
    getStatusColor(order) {
      // 如果有退款状态，使用退款相关颜色
      if (order.refundStatus !== undefined && order.refundStatus !== null) {
        switch (order.refundStatus) {
          case 1:
          case 2:
            return '#FF9500' // 橙色：等待审核/审核中
          case 3:
            return '#34C759' // 绿色：退款已通过
          case 4:
            return '#FF3B30' // 红色：退款已拒绝
          default:
            break
        }
      }
      
      // 如果订单状态是已退款，使用绿色
      if (order.status === 8) {
        return '#34C759'
      }
      
      // 如果订单状态是退款审核中，使用橙色
      if (order.status === 9) {
        return '#FF9500'
      }
      
      // 其他状态使用统一的订单状态工具函数
      return getUnifiedStatusColor(2, order.status)
    },

    // 获取友好的状态显示文本
    getDisplayStatusText(order) {
      // 如果有退款状态，优先显示退款相关信息
      if (order.status === 9 && order.refundStatus !== undefined && order.refundStatus !== null) {
        switch (order.refundStatus) {
          case 1:
            return '发布人申请退款，等待审核'
          case 2:
            return '退款审核中'
          case 3:
            return '退款已通过'
          case 4:
            return '退款已拒绝'
          default:
            break
        }
      }
      
      // 如果订单状态是已退款，显示友好提示
      if (order.status === 8) {
        return '订单已退款'
      }
      
      // 如果订单状态是退款审核中，显示友好提示
      if (order.status === 9) {
        return '发布人申请退款，等待审核'
      }
      
      // 其他状态使用原来的状态文本，如果为空则使用默认状态
      return order.statusText || this.getDefaultStatusText(order.status)
    },

    // 获取默认状态文本
    getDefaultStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '待接单', 
        2: '待取件',
        3: '配送中',
        4: '已送达',
        5: '待结算',
        6: '已完成',
        7: '已取消',
        8: '已退款',
        9: '退款审核中'
      }
      return statusMap[status] || '未知状态'
    }
  }
}
</script>

<style scoped>
.my-orders {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #F5F5F5;
}

.tabs {
  display: flex;
  background: #fff;
  padding: 0 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 28rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #4ECDC4;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 6rpx;
  background: #4ECDC4;
  border-radius: 3rpx;
}

.order-list {
  flex: 1;
  padding: 24rpx;
}

.empty-state {
  padding: 200rpx 0;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 48rpx;
}

.btn-go-available {
  width: 300rpx;
  height: 72rpx;
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: #fff;
  font-size: 28rpx;
  border-radius: 36rpx;
  border: none;
}

.order-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 1rpx solid #F0F0F0;
}

.order-header .left {
  display: flex;
  align-items: center;
}

.order-header .icon {
  font-size: 40rpx;
  margin-right: 12rpx;
}

.order-header .name {
  font-size: 32rpx;
  font-weight: bold;
}

.order-header .status {
  font-size: 28rpx;
  font-weight: bold;
}

.address-section {
  background: #F8F9FA;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
}

.address-item {
  display: flex;
  margin-bottom: 16rpx;
}

.address-item:last-child {
  margin-bottom: 0;
}

.address-item .label {
  min-width: 100rpx;
  font-size: 26rpx;
  color: #666;
}

.address-item .value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.divider {
  height: 1rpx;
  background: #E0E0E0;
  margin: 16rpx 0;
}

.order-info {
  margin-bottom: 24rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12rpx;
  font-size: 26rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-row .label {
  color: #999;
}

.info-row .value {
  color: #666;
}

.info-row .earning {
  color: #4ECDC4;
  font-weight: bold;
  font-size: 30rpx;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16rpx;
}

.order-actions button {
  padding: 16rpx 32rpx;
  font-size: 26rpx;
  border-radius: 8rpx;
  border: none;
}

.btn-primary {
  background: linear-gradient(135deg, #4ECDC4, #44A08D);
  color: #fff;
}

.btn-text {
  background: transparent;
  color: #4ECDC4;
  border: 1rpx solid #4ECDC4 !important;
}

.btn-disabled {
  background: #e0e0e0;
  color: #999;
  border: none;
  opacity: 0.6;
}

.loading-more,
.no-more {
  text-align: center;
  padding: 32rpx;
  font-size: 24rpx;
  color: #999;
}

/* 弹窗样式 */
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.upload-popup {
  width: 600rpx;
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.popup-close {
  font-size: 36rpx;
  color: #999;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-content {
  padding: 32rpx;
}

.popup-footer {
  display: flex;
  gap: 24rpx;
  padding: 32rpx;
  border-top: 1px solid #f0f0f0;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: 600;
  border: none;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
}

.btn-confirm {
  background: linear-gradient(135deg, #4ECDC4 0%, #44A08D 100%);
  color: #fff;
}
</style>

